from django.http import HttpResponse
from django.shortcuts import render, redirect

from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse,HttpResponseRedirect
# 登录处理
def signin(request):
    if request.method == 'GET':
        return render(request, 'student/login.html')
    # 从 HTTP POST 请求中获取用户名、密码参数
    userName = request.POST.get('username')
    passWord = request.POST.get('password')

    # 使用 Django auth 库里面的 方法校验用户名、密码
    user = authenticate(username=userName, password=passWord)
    
    # 如果能找到用户，并且密码正确
    if user is not None:
        if user.is_active:
            login(request, user)
            if user.is_superuser:
                # 在session中存入用户类型
                # request.session['usertype'] = 'mgr'
                # return HttpResponseRedirect('/admin')
                return JsonResponse({'ret': 0})
            else:
                print(userName)     
                return redirect('/student/show_courses/')
                # return JsonResponse({'ret': 1, 'msg': '请使用管理员账户登录'})
        else:
            return JsonResponse({'ret': 0, 'msg': '用户已经被禁用'})
        
    # 否则就是用户名、密码有误
    else:
        return JsonResponse({'ret': 1, 'msg': 'username or password error'})


# 登出处理
def signout( request):
    # 使用登出方法
    logout(request)
    return redirect('/login')

# def login(request):
#     if request.method == 'GET':
#         return render(request, 'login.html')
#     else:
#         user = request.POST.get('username')
#         pwd = request.POST.get('pwd')
#         # print(user, pwd)
#         if user == 'root' and pwd == '123123':
#             # 登录成功
#             return render(request, 'index.html', {'user': user})
#         else:
#             # 登陆失败
#             return render(request, 'login.html', {'msg': "用户名或密码错误!!"})

